package com.kanshu.ksgb.fastread.doudou.module.bookcity.view;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs;
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader;
import com.kanshu.ksgb.fastread.doudou.common.supertextview.SuperTextView;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.ItemRefreshBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.SelectedBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.utils.BookCityUtils;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static com.kanshu.ksgb.fastread.doudou.app.constants.Constants.BookCityModuleType.TYPE_SELECTED_QUANZHANCHANGDU;
import static com.kanshu.ksgb.fastread.doudou.base.baseui.SwipeBackActivity.ACTION_DESTORY;

/**
 * Created by wcy on 18/5/15.
 */

public class AdSelectedSixLayout extends LinearLayout implements IRefresh<SelectedBean> {
    @BindView(R.id.label)
    TextView mLabel;
    @BindView(R.id.book_container)
    LinearLayout mBookContainer;
    @BindView(R.id.ad_container)
    FrameLayout mAdContainer;
    ItemRefreshBean mItemRefreshBean;
    SparseArray<View> mSparseArray = new SparseArray<>();
    HashMap<String, Boolean> mShowNormalDatas = new HashMap<>();
    boolean mShowedAd;
    boolean mShowLeftPicRightTextAd;
    String mType;
    @BindView(R.id.change)
    TextView mChange;
    @BindView(R.id.change_tip)
    ImageView mChangeTip;

    public Subject<Integer> lifeCyclerSubject = PublishSubject.create();
    BookCityPresenter presenter;
    @BindView(R.id.ad_divider)
    LinearLayout mAdDivider;

    public AdSelectedSixLayout(Context context) {
        super(context);
        init();
    }

    public AdSelectedSixLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AdSelectedSixLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        presenter = new BookCityPresenter(lifeCyclerSubject);
        setOrientation(VERTICAL);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_ad_selected_six_layout, this);
        ButterKnife.bind(view);
    }

    @Override
    public void refresh(SelectedBean selectedBean, Object object) {
        if (selectedBean == null || object == null) {
            return;
        }
        BookCityUtils.rotateCancel(mChangeTip);
        mItemRefreshBean = (ItemRefreshBean) object;
        mLabel.setText(selectedBean.name);
        mType = selectedBean.type;
        if (TextUtils.equals(mType, Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI3)) {
            mChange.setText("换分类");
        } else {
            mChange.setText("换一换");
        }
        mLabel.setCompoundDrawablesWithIntrinsicBounds(mItemRefreshBean.selectionIcon, 0, 0, 0);
        if (!Utils.isEmptyList(selectedBean.list)) {
            if (mShowNormalDatas.get(mType) != null
                    && mShowNormalDatas.get(mType)) {
                return;
            }
            if (selectedBean.list.size() > 3) {
                selectedBean.list = selectedBean.list.subList(0, 3);
            }
            for (int i = 0; i < selectedBean.list.size(); i++) {
                View view = mSparseArray.get(i);
                if (view == null) {
                    view = LayoutInflater.from(getContext()).inflate(R.layout.item_book_layout, null);
                    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                    mBookContainer.addView(view, params);
                    mSparseArray.put(i, view);
                }
                ImageView imageView = (ImageView) view.findViewById(R.id.cover);
                TextView tv = (TextView) view.findViewById(R.id.book_title);
                TextView tvDesc = (TextView) view.findViewById(R.id.book_desc);
                TextView tvAuthor = (TextView) view.findViewById(R.id.author);
                TextView tvLable = (TextView) view.findViewById(R.id.book_label);
                SuperTextView tvStatus = (SuperTextView) view.findViewById(R.id.book_status);
                View bottomContainer = view.findViewById(R.id.bottom_container);
                DisplayUtils.visible(bottomContainer);
                GlideImageLoader.load(selectedBean.list.get(i).cover_url, imageView);
                tv.setText(selectedBean.list.get(i).book_title);
                tvDesc.setText(selectedBean.list.get(i).book_intro);
                tvAuthor.setText(selectedBean.list.get(i).author_name);
                tvLable.setText(BookUtils.getBookLabel(selectedBean.list.get(i)));
                tvStatus.setText(BookUtils.getBookStatus(selectedBean.list.get(i)));
                BookUtils.setStatusBg(tvStatus, selectedBean.list.get(i));
                DisplayUtils.visible(imageView);
                FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.ad_container);
                if (frameLayout.getChildCount() > 1) {
                    frameLayout.getChildAt(1).setVisibility(GONE);
                }
                final int pos = i;
                view.setOnClickListener(v -> {
                    ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", selectedBean.list.get(pos).book_id);
                    BookCityUtils.takeIf(mItemRefreshBean, TYPE_SELECTED_QUANZHANCHANGDU, () -> {
                        AdPresenter.pvuvStatics(pos,
                                R.string.SCTUIJIAN7_POSITION1,
                                R.string.SCTUIJIAN7_POSITION2,
                                R.string.SCTUIJIAN7_POSITION3);
                    });
                });
            }
            mShowNormalDatas.put(mType, true);
        }
        DisplayUtils.gone(mAdContainer, mAdDivider);
        // 添加广告 上文下图
        if (mItemRefreshBean.type.equals(TYPE_SELECTED_QUANZHANCHANGDU)
                && ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_QUANZHANCHANGDU_BOTTOM_JX_6)) != null) {
            DisplayUtils.visible(mAdContainer, mAdDivider);
            if (!mShowedAd) {
                AdUtils.fetchAdUtil((Activity) getContext(), mAdContainer, null, ADConfigBean.POSITION_QUANZHANCHANGDU_BOTTOM_JX_6, AdStyleBean.IMAGE_TEXT_STYLE, 0, new BaseAdListener() {
                    @Override
                    public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
                        mShowedAd = true;
                        DisplayUtils.visible(mAdContainer, mAdDivider);
                    }

                    @Override
                    public void onAdLoadFailed() {
                        mShowedAd = false;
                        DisplayUtils.gone(mAdContainer, mAdDivider);
                    }

                    @Override
                    public void onAdClicked() {
                    }

                    @Override
                    public void onADClosed() {
                        mShowedAd = false;
                    }

                    @Override
                    public void onBackAd(@NotNull Object ad) {
                    }
                });
            }
        }
        // 左图右文
        if (isShowLeftPicRightText()) {
            if (mShowLeftPicRightTextAd) {
                return;
            }
            if (!Utils.isEmptyList(selectedBean.list)) {
                AdUtils.Companion.fetchAdUtil((Activity) getContext(), null, null, ADConfigBean.POSITION_FEMALE_JIAKONGLISHI_NP_6, AdStyleBean.BOOK_COVER_STYLE, R.layout.item_book_layout, new BaseAdListener() {
                    @Override
                    public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
                        if (selectedBean.list.size() >= 3
                                || mBookContainer.getChildCount() >= 3) {
                            mBookContainer.removeViewAt(mBookContainer.getChildCount() - 1);
                        }
                        mBookContainer.addView(view);
                        mShowLeftPicRightTextAd = true;
                        TextView tv1 = (TextView) view.findViewById(R.id.book_label);
                        TextView tv2 = (TextView) view.findViewById(R.id.book_status);
                        DisplayUtils.gone(tv1, tv2);
                    }

                    @Override
                    public void onAdLoadFailed() {
                        mShowLeftPicRightTextAd = false;
                    }

                    @Override
                    public void onAdClicked() {

                    }

                    @Override
                    public void onADClosed() {
                    }

                    @Override
                    public void onBackAd(@NotNull Object ad) {

                    }
                });
            }
        }
    }

    @Override
    public void onError(int code, String desc) {
        BookCityUtils.rotateCancel(mChangeTip);
    }

    @Override
    public void reset() {
        if (mShowNormalDatas != null) {
            mShowNormalDatas.clear();
        }
        mShowedAd = false;
        mShowLeftPicRightTextAd = false;
    }

    @OnClick(R.id.change_container)
    public void onViewClicked() {
        BookCityUtils.rotate(mChangeTip);
        mShowedAd = false;
        mShowLeftPicRightTextAd = false;
        mShowNormalDatas.put(mType, false);
        if (TextUtils.equals(mType, Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI3)) {
            BookCityUtils.switchFemaleCategory(mItemRefreshBean, this, null, presenter);
        } else {
            BookCityUtils.refreshModuleInfos(mItemRefreshBean, this, presenter);
        }

        BookCityUtils.takeIf(mItemRefreshBean, TYPE_SELECTED_QUANZHANCHANGDU, () -> {
            AdPresenter.pvuvStatics(R.string.SCTUIJIAN7_HUANYIHUAN);
        });

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        lifeCyclerSubject.onNext(ACTION_DESTORY);
    }

    private boolean isShowLeftPicRightText() {
        return TextUtils.equals(mType, Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI3) && ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_FEMALE_JIAKONGLISHI_NP_6)) != null;
    }

}
